package redis

import (
	"context"
	"git.blindage.org/21h/redis-operator/pkg/controller/manifests"
	blindagev1alpha1 "git.blindage.org/21h/redis-operator/pkg/apis/blindage/v1alpha1"
	"github.com/go-logr/logr"
	corev1 "k8s.io/api/core/v1"
	"sigs.k8s.io/controller-runtime/pkg/client"
	"sigs.k8s.io/controller-runtime/pkg/reconcile"
)

func (r *ReconcileRedis) deleteDependentResoucePVC(reqLogger logr.Logger, cr *blindagev1alpha1.Redis) (reconcile.Result, error) {
	reqLogger.Info("Deleting PVC")
	if manifests.ContainsString(cr.ObjectMeta.Finalizers, "PurgePVC") {
		foundDependentPVCs := &corev1.PersistentVolumeClaimList{}

		labels := manifests.MergeLabels(manifests.BaseLabels(cr))

		err := r.client.List(context.TODO(), client.InNamespace(cr.Namespace).MatchingLabels(labels), foundDependentPVCs)
		if err != nil {
			reqLogger.Info("Listing dependent PVCs error", "Namespace", cr.Namespace, ".Name", cr.Name)
			return reconcile.Result{}, err
		}

		for _, pvc := range foundDependentPVCs.Items {
			if err := r.client.Delete(context.Background(), &pvc); err != nil {
				reqLogger.Info("Deleting PVC failed")
				return reconcile.Result{}, err
			}
		}
	}
	return reconcile.Result{}, nil
}

func (r *ReconcileRedis) reconcileFinalizers(reqLogger logr.Logger, instance *blindagev1alpha1.Redis) (reconcile.Result, error) {
	reqLogger.Info("Processing finalizers", "Namespace", instance.Namespace, ".Name", instance.Name)
	finalizersList := []string{"PurgePVC"}
	if instance.ObjectMeta.DeletionTimestamp.IsZero() {
		instance.ObjectMeta.Finalizers = finalizersList
		if err := r.client.Update(context.Background(), instance); err != nil {
			return reconcile.Result{}, err
		}

	} else {
		if instance.Spec.PersistentVolumePurge {
			_, err := r.deleteDependentResoucePVC(reqLogger, instance)
			if err != nil {
				reqLogger.Info("PVC deletion error", "Namespace", instance.Namespace, ".Name", instance.Name)
				return reconcile.Result{}, err
			}
		}

		instance.ObjectMeta.Finalizers = manifests.RemoveString(instance.ObjectMeta.Finalizers, "PurgePVC")
		if err := r.client.Update(context.Background(), instance); err != nil {
			reqLogger.Info("Removing PVC finalizer failed")
			return reconcile.Result{}, err
		}
	}

	return reconcile.Result{}, nil
}
